import axios from 'axios'
import { ElMessage, type MessageParamsWithType } from 'element-plus';
import router from "../router";
import config from '../config'

// 创建axios实例
// 创建请求时可以用的配置选项

// 配后端数据的接收方式application/json;charset=UTF-8或者application/x-www-form-urlencoded;charset=UTF-8
const contentType = 'application/json;charset=UTF-8'

// const apiUrl = config.VITE_APP_BASE_API
// console.log(apiUrl)
let apiUrl;

if (import.meta.env.MODE === 'production') {
    // 生产环境逻辑
    apiUrl = config.VITE_ENV_API
} else {
    // 开发环境逻辑
    apiUrl = config.VITE_APP_BASE_API
}
const instance = axios.create({
    /**
     * 是否携带cookie,注意若携带cookie后端必须配置
     * 1.Access-Control-Allow-Origin为单一域名(具体到IP + port,用localhost貌似不行)
     * 2.需要带上响应头Access-Control-Allow-Credentials
     */
    // withCredentials: true,
    timeout: 60000,
    baseURL: apiUrl,
    headers: {
        'Content-Type': contentType
    }
})
// axios的全局配置
instance.defaults.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded'
}
instance.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
}
//instance.defaults.headers['Access-Control-Allow-Origin']='*'

// 添加请求拦截器(post只能接受字符串类型数据)
instance.interceptors.request.use(
    (config: { headers: { satoken: string; }; }) => {
        const satoken = localStorage.getItem('satoken')
        if (satoken) {
            config.headers.satoken = satoken
        }
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)
const errorHandle = (status: number, other: MessageParamsWithType) => {
    switch (status) {
        case 400:
            ElMessage.error('信息校验失败')
            break
        case 401:
            // @ts-nocheck
            ElMessage.error('认证失败')
            break
        case 403:
            ElMessage.error('token校验失败')
            break
        case 404:
            ElMessage.error('请求的资源不存在')
            break
        default:
            ElMessage.error(other)
            break
    }
}

// 添加响应拦截器
instance.interceptors.response.use(
    (    // 响应包含以下信息data,status,statusText,headers,config
        res: { data: { code: string; }; }) => {

        if (res.data.code && res.data.code === '9999') {
            router.push('/sso-login?back=' + encodeURIComponent(window.location.href))
        }
        // 请求通用处理
        return res.data
    },
    (err: { response: any; }) => {
        // Message.error(err)
        const { response } = err
        if (response) {
            errorHandle(response.status, response.data)
            return Promise.reject(response)
        }
        ElMessage.error('请求失败')
        return true
    }
)
export default instance
